from flask import Blueprint, jsonify, request, render_template
from .models import *
from .exts import *


blue = Blueprint('user', __name__)


# 添加密码
@blue.route('/passwords', methods=['POST'])
def create_password():
    data = request.get_json()
    new_password = Password(
        software_name=data['software_name'],
        account=data['account'],
        password=data['password']
    )
    db.session.add(new_password)
    db.session.commit()
    return jsonify({"status":"success",'message': 'Password created successfully', 'id': new_password.id}), 201


# 获取所有密码
@blue.route('/passwords', methods=['GET'])
def get_passwords():
    passwords = Password.query.all()
    passwords_list = []
    # 获取所有的数据并放入passwords_list中
    for password in passwords:
        passwords_list.append({
            'id': password.id,
            'software_name': password.software_name,
            'account': password.account,
            'password': password.password
        })

    return jsonify(passwords_list)


# 更新密码
@blue.route('/passwords/<int:id>', methods=['PUT'])
def update_password(id):
    data = request.get_json()
    password = Password.query.get_or_404(id)
    password.software_name = data['software_name']
    password.account = data['account']
    password.password = data['password']
    db.session.commit()
    return jsonify({'message': 'Password updated successfully'})


# 删除密码
@blue.route('/passwords/<int:id>', methods=['DELETE'])
def delete_password(id):
    password = Password.query.get_or_404(id)
    db.session.delete(password)
    db.session.commit()
    return jsonify({'message': 'Password deleted successfully'})


# 访问
@blue.route("/",methods=['GET'])
def index():
    # 返回index.html
    return render_template("index.html")
